import { app, BrowserWindow, globalShortcut, screen } from 'electron';
import * as path from 'path';
import * as fs from 'fs';
import * as url from 'url';

const os = require('os');

let win: any = null;
const args = process.argv.slice(1),
    serve = args.some(val => val === '--serve');

process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = '1';

function createWindow(): BrowserWindow {

  const size = screen.getPrimaryDisplay().workAreaSize;

  win = new BrowserWindow({
    x: 0,
    y: 0,
    width: size.width,
    height: size.height,
    webPreferences: {
      nodeIntegration: true,
      allowRunningInsecureContent: (serve),
      contextIsolation: false,  // false if you want to run e2e test with Spectron
    },
  });

  win.removeMenu();
  win.setAspectRatio(16 / 9);

  if (serve) {
    const debug = require('electron-debug');
    debug();

    require('electron-reloader')(module);
    win.loadURL('http://localhost:4200');
    win.webContents.openDevTools();
  } else {
    let pathIndex = './index.html';

    if (fs.existsSync(path.join(__dirname, '../dist/index.html'))) {
      pathIndex = '../dist/index.html';
    }

    win.loadURL(url.format({
      pathname: path.join(__dirname, pathIndex),
      protocol: 'file:',
      slashes: true,
    }));

    win.webContents.on('did-fail-load', () => {
      win.loadURL(url.format({
        pathname: path.join(__dirname, pathIndex),
        protocol: 'file:',
        slashes: true,
      }));
    });

    let platform = os.platform();
    if (platform === 'darwin') {
      globalShortcut.register('Command+Option+I', () => {
        win.webContents.openDevTools();
      });
    } else if (platform === 'linux' || platform === 'win32') {
      globalShortcut.register('Control+Shift+I', () => {
        win.webContents.openDevTools();
      });
    }

  }


  win.on('closed', () => {
    win = null;
  });

  return win;
}

try {
  app.on('ready', () => setTimeout(createWindow, 400));

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit();
    }
  });

  app.on('activate', () => {
    if (win === null) {
      createWindow();
    }
  });

} catch (e) {
  // throw e;
}
